<?php

namespace App\Http\Middleware;

use App\Models\Auth\User;
use Spatie\Permission\Exceptions\UnauthorizedException;

class PermissionMiddleware extends \Spatie\Permission\Middlewares\PermissionMiddleware
{
    public function handle($request, \Closure $next, $permission, $guard = null)
    {
        $authGuard = app('auth')->guard($guard);

        if ($authGuard->guest()) {
            throw UnauthorizedException::notLoggedIn();
        }

        $permissions = is_array($permission)
            ? $permission
            : explode('|', $permission);

        $user = $authGuard->user();

        if ($user instanceof User) {

            $user = $user->reassignPermissions();

            foreach ($permissions as $permission) {
                if ($user->can($permission)) {
                    return $next($request);
                }
            }

            throw UnauthorizedException::forPermissions($permissions);
        }
        return $next($request);
    }
}
